package com.nuanshui.framework.springContext;


import com.nuanshui.framework.lang.SysStringUtils;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * @author 陈泽权
 * 
 *         下午8:18:34
 */
public class SpringContextUtil implements ApplicationContextAware,BeanPostProcessor{
		 

	private static ApplicationContext applicationContext;


	public SpringContextUtil() {
		System.out.println("-----------------");
	}
	
	public Object getPropertyConfigurer() {
		return propertyConfigurer;
	}

	public void setPropertyConfigurer(Properties propertyConfigurer) {
		this.propertyConfigurer = propertyConfigurer;
	}

	private Properties propertyConfigurer;

	@Override
	public void setApplicationContext(
			final ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(final String name) {
		try {
			return (T) applicationContext.getBean(name);
		} catch (Exception e) {
		}
		return null;
		
	}
	@SuppressWarnings("unchecked")
	public static <T> T getBean(final Class<T> clazz) {
		return (T) getBean(SysStringUtils.toLowerCase(clazz.getSimpleName(), 0,
				1));
	}
	
	/**
	 * 转化为小写
	 * 
	 * @param str
	 *            要被转化的字符串
	 * @param start
	 *            开始的位置
	 * @param end
	 *            结束的位置
	 * @return
	 */
	public static String toLowerCase(final String str, final int start,
			final int end) {

		if (StringUtils.isEmpty(str)) {
			return str;
		}
		StringBuilder sb = new StringBuilder();
		sb.append(str.substring(0, start));
		sb.append(str.substring(start, end).toLowerCase());
		sb.append(str.substring(end));
		return sb.toString();
	}



	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return  bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		
		return bean;
	}
}
